@echo off
:: Batch script by affggh
:: Version : 1.0
:: Using adb command check device connect state

:: Set replace defaults
:: max_retries %1 set to 0 to inlimit loop until detect device
set max_retries=20
:: wait_retries %2 seconds once loop
set wait_retries=0

:: Defaults
if not defined adb set "adb=%~dp0adb"
if not defined fastboot set "fastboot=%~dp0fastboot"
if not defined max_retries set max_retries=20
if not defined wait_retries set wait_retries=2

:: Example
:: %3 is variable name to recive var
:: Use this to receive device state
call :chk_state %max_retries% %wait_retries% state
if defined state (
    echo state=%state%
) else (
    echo Device not found!
)
exit /b 0

:chk_state
setlocal
rem Start adb server
%adb% start-server
set "max_retries=%1"
set "wait_retries=%2"
set "state_list=device recovery rescue sideload bootloader disconnect"
if not defined count set count=1
:chk_state_loop
for /f %%i in ('%adb% get-state 2^>^&1') do (
    for %%j in (%state_list%) do (
        if /I "%%i"=="%%j" set state=%%j & goto :chk_state_end
        if "%%i"=="error:" (
            for /f "tokens=2 delims= " %%k in ('%fastboot% devices') do (
                if /I "%%k"=="fastboot" set state=%%k & goto :chk_state_end
            )
        )
    )
)
rem echo Device not found, retrying... count[%count%] max_retries[%max_retries%] wait_retries[%wait_retries%]
if not "%wait_retries%"=="0" timeout /t %wait_retries% /nobreak > nul
if not "%max_retries%"=="%count%" set /a count+=1 & goto chk_state_loop
:chk_state_end
endlocal & set %3=%state%
goto :eof